﻿using Cdhpy.Util;
using CdhpyScheduler.Core;
using CdhpyScheduler.WebHost.Models;
using CdhpyScheduler.WebHost.PubMethod;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CdhpyScheduler.WebHost.Controllers
{
    public class ApiController : Controller
    {
        [AcceptVerbs("GET", "POST")]
        public string Heartbeat()
        {
            return "ok";
        }

        public string AddPersistentJobs(List<JobAPIModel> _jobs)
        {
            if (_jobs?.Count > 0 == false)
                return "parameter can not be empty";
            
            //convert
            List<JobModel> jobs = MapperWrapper.Map<List<JobAPIModel>, List<JobModel>>(_jobs);

            //add
            foreach (var job in jobs)
            {
                if (Job.jc.CheckJobDuplication(job)) //if already scheduled and arguments are the same, pass
                    continue;

                Job.jc.TryRemoveJob(job.jobKey_name, job.jobKey_group);
                Job.jc.Create(job);
            }

            //persistent
            var currentJobs = Job.jc.GetAllScheduledJobs();
            try
            {
                Job.OverwriteJobFile(currentJobs);
            }
            catch(Exception ex)
            {
                return ex.Message;
            }

            return "ok";
        }

        [HttpPost]
        public string AddTemporaryJob(NewTempJobModel item)
        {
            if (item == null || string.IsNullOrEmpty(item.url))
                return "data or url is null";

            if (item.fire_delay_seconds == 0)
                return "fire_delay can not be zero";

            JobModel job = new JobModel();
            job.http_method = item.httpVerb?.ToLower() == "get" ? "get" : "post";
            job.interval_hours = 0;
            job.interval_minutes = 0;
            job.interval_seconds = item.fire_delay_seconds;
            job.interval_type = JobModel_IntervalType.每间隔一段时间;
            job.isTemp = true;
            job.jobKey_group = "Temporary";
            job.jobKey_name = "temp_" + item.task_client_id;
            job.remark = item.remark;
            job.repeate_count = 1 ;
            job.url = item.url;

            Job.jc.TryRemoveJob(job.jobKey_name, job.jobKey_group);

            DateTime dt = DateTime.UtcNow.AddSeconds(item.fire_delay_seconds);
            Job.jc.Create_Temp(job, dt);

            return "ok";
        }

        [HttpPost]
        public string RemoveFinished()
        {
            var jobs = Job.jc.GetRunningScheduledJobs();
            foreach (var job in jobs)
            {
                var trigger = Job.jc.GetTriggerTime(job.trigger_name, job.jobKey_group);
                if (!trigger.Key.HasValue || !trigger.Value.HasValue)
                    Job.jc.TryRemoveJob(job.trigger_name, job.jobKey_group);
            }
            return "ok";
        }

        public JsonResult GetCurrentJobs()
        {
            var jobs = Job.jc.GetRunningScheduledJobs();
            List<JobVM> list = new List<JobVM>();
            foreach (var job in jobs)
            {
                //base
                var item = new JobVM
                {
                    jobKey = job.jobKey_name,
                    repeat = job.repeate_count,
                    remark = job.remark
                };

                //trigger time
                var trigger = Job.jc.GetTriggerTime(job.trigger_name, job.jobKey_group);
                item.lastTrigger = trigger.Key.HasValue ? Timestamp.Get(trigger.Key.Value) : 0;
                item.nextTrigger = trigger.Value.HasValue ? Timestamp.Get(trigger.Value.Value) : 0;

                //interval type
                if (job.interval_type == JobModel_IntervalType.每天)
                {
                    string tem = $"每天 {job.interval_hours.ToString().PadLeft(2, '0')}:{job.interval_minutes.ToString().PadLeft(2, '0')}:{job.interval_seconds.ToString().PadLeft(2, '0')}";
                    item.interval = tem;
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("每隔 ");
                    if (job.interval_days > 0)
                        sb.Append(job.interval_days).Append("天");
                    if (job.interval_hours > 0)
                        sb.Append(job.interval_hours).Append("小时");
                    if (job.interval_minutes > 0)
                        sb.Append(job.interval_minutes).Append("分钟");
                    if (job.interval_seconds > 0)
                        sb.Append(job.interval_seconds).Append("秒");
                    item.interval = sb.ToString();
                }

                list.Add(item);
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetCurrentJobsGrid()
        {
            var jobs = Job.jc.GetRunningScheduledJobs();
            List<JobVM> list = new List<JobVM>();
            foreach (var job in jobs)
            {
                //base
                var item = new JobVM
                {
                    jobKey = job.jobKey_name,
                    repeat = job.repeate_count,
                    remark = job.remark
                };

                //trigger time
                var trigger = Job.jc.GetTriggerTime(job.trigger_name, job.jobKey_group);
                item.lastTrigger = trigger.Key.HasValue ? Timestamp.Get(trigger.Key.Value) : 0;
                item.nextTrigger = trigger.Value.HasValue ? Timestamp.Get(trigger.Value.Value) : 0;

                //interval type
                if (job.interval_type == JobModel_IntervalType.每天)
                {
                    string tem = $"每天 {job.interval_hours.ToString().PadLeft(2, '0')}:{job.interval_minutes.ToString().PadLeft(2, '0')}:{job.interval_seconds.ToString().PadLeft(2, '0')}";
                    item.interval = tem;
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("每隔 ");
                    if (job.interval_days > 0)
                        sb.Append(job.interval_days).Append("天");
                    if (job.interval_hours > 0)
                        sb.Append(job.interval_hours).Append("小时");
                    if (job.interval_minutes > 0)
                        sb.Append(job.interval_minutes).Append("分钟");
                    if (job.interval_seconds > 0)
                        sb.Append(job.interval_seconds).Append("秒");
                    item.interval = sb.ToString();
                }

                list.Add(item);
            }

            var response = new LayTableModel<JobVM>
            {
                count = list.Count,
                data = list,
                msg = ""
            };

            return Json(response, JsonRequestBehavior.AllowGet);
        }
    }
}